package hilos;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.TimerTask;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import android.app.Activity;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.bd.dal;
import com.bd.datos;
import com.encuestas.utilidades;
import com.gio.lib.conexion.sync;

public class uploadTime  extends TimerTask{
	

	final Context cnt;

	dal db;
 public uploadTime( Context  cnt) {
		super();
		this.cnt= cnt;
		

	

	}

	@Override
	public void run() {
		
		db = new dal(this.cnt);
		
	//long tamano=db.sizeBD();

		 List<String>  json=db.noTransmitidos("proyectos");
		try {
			for (int i = 0; i< json.size();i++)
			{
				String param ="[" +  json.get(i) + "]";
				HttpParams params = new BasicHttpParams();
				params.setParameter("MAX_TOTAL_CONNECTIONS", 100);
				HttpConnectionParams.setConnectionTimeout(params, 20000);
				HttpConnectionParams.setSoTimeout(params, 20000);
				HttpClient cliente = new DefaultHttpClient(params);
				//HttpPost post = new HttpPost("http://10.0.2.2/guardarmovil.php");
				HttpPost post = new HttpPost("http://r-visual.com/guardarfastjson.php");
				List<NameValuePair> l = new ArrayList<NameValuePair>();
				l.add(new BasicNameValuePair("jsonw", param));
				UrlEncodedFormEntity datos = new UrlEncodedFormEntity(l);
				post.setEntity(datos);
				if(!sync.chequeaConexionInternet(this.cnt))
				{
					Log.e("SIN CONEXION A INTERNET", "error de conexion en internet");
					return ;
				
				}
			
				HttpResponse respuesta=cliente.execute(post);
			
				String resultado;
				HttpEntity  entiti = respuesta.getEntity();
				if (entiti!= null)
				{
					resultado=utilidades.ObtenerStRes(entiti.getContent());
					cliente.getConnectionManager().shutdown();
					db.changeEstadoEnviados(resultado);
					Log.i("ENCUESTA EN AUTOUPLOAD EXITOSA", "SE ENVIO CON AUTOUPLOAD");
			
				}
				else
				{
					
					//aca cuando no se reciva nda del servidor
					
				}
				
			}
		
			
		} catch (ClientProtocolException e) {
			
			
		return ;
		
		} catch (IOException e) {
			
			
			return ;
		}
		catch (Exception ex){
			
			Log.e("error", ex.getMessage());
		}
		
			
		
	}
	
	
	
}
